from fastapi import APIRouter, Depends, HTTPException, Form
from pydantic import BaseModel
from fastapi.security import HTTPBearer, HTTPAuthorizationCredentials
import jwt
from datetime import datetime, timedelta
from db_manage.user_manage import register_user, login_user, generate_invite_code, check_login_status, logout_user
from database import get_db
from sqlalchemy.orm import Session


router = APIRouter(prefix="/api", tags=["users"])


security = HTTPBearer()

class UserForm(BaseModel):
    username: str
    password: str
    email: str = None
    invite_code: str
class LoginForm(BaseModel):
    username: str
    password: str

@router.post("/register")
async def api_register_user(
    user: UserForm,
    db: Session = Depends(get_db)
):
    result = register_user(user.username, user.password, user.email, user.invite_code, db)
    if "error" in result:
        raise HTTPException(status_code=400, detail=result["error"])
    return result

@router.post("/login")
async def api_login_user(
    loginData: LoginForm,
    db: Session = Depends(get_db)
):
    result = login_user(loginData.username, loginData.password, db)
    if "error" in result:
        raise HTTPException(status_code=401, detail=result["error"])
    return result

@router.post("/generate-invite-code")
async def api_generate_invite_code(db: Session = Depends(get_db)):
    return generate_invite_code(db)
    
@router.post("/check-login")
async def api_check_login(
    credentials: HTTPAuthorizationCredentials = Depends(security),
    db: Session = Depends(get_db)
):
    result = check_login_status(credentials.credentials, db)
    if "error" in result:
        raise HTTPException(status_code=401, detail=result["error"])
    return result
    
@router.post("/logout")
async def api_logout(
    credentials: HTTPAuthorizationCredentials = Depends(security),
    db: Session = Depends(get_db)
):
    result = logout_user(credentials.credentials, db)
    if "error" in result:
        raise HTTPException(status_code=401, detail=result["error"])
    return result
